from __future__ import absolute_import, unicode_literals
# from __future__ import absolute_import, unicode_literals
from celery import shared_task
import time
import json
from tools.myredis import mredis
from tools.logoAgent import logo_agent
from user.models import UserProfile
from tools.BaiduTool import baidu
import logging

logger = logging.getLogger(__name__)


@shared_task
def baidu_task():
    print("百度定时任务gogogo")
    # 先获取长度
    length = mredis.llen('idcardlist')
    if length > 0:
        print("有数据")
        # 从redis list队列中获取3条信息

        # 获取任务但不弹出(防止处理失败丢失任务)
        imglist = mredis.lrange('idcardlist', 0, 2)  # 0-2
        for url in imglist:
            print(url)
            # 调用百度api接口
            try:
                mes = baidu.idcard(url)
                # {"name":"zs","code":"234234"}
                # 存入redis
                mredis.set(url,json.dumps(mes))
                logger.info(f"图片处理完成: {url}")
                # 但是你在这里调用百度api也咩任何用途，所以要写一个查询状态的接口
                # 从队列中移除已处理的任务
                mredis.lrem('idcardlist', 1, url)
            except Exception as e:
                logger.error(f"处理图片时发生错误: {url}, 错误: {str(e)}")
                # 可以选择将失败的任务保留在队列中重试，或移到另一个队列





#     blist = r.list_lrange('baiduurllist', 0, 10)
#     if blist:
#         for i in blist:
#             picurl = i.decode()
#             # 调用百度api接口
#             mes = bdapi.fontmessage(picurl)
#             # 存入redis {"name":"zs","code":"234234"}
#             r.set_str(picurl, json.dumps(mes))
#             r.list_del('baiduurllist', picurl)
#     print("调用百度api接口")



@shared_task
def generate_user_logo_task():
    """异步任务：从Redis队列中获取用户Logo生成请求并处理，将结果存入Redis"""
    try:
        print("[Logo异步任务] 开始处理Logo生成队列")

        # 从redis list中获取3条信息
        logo_requests = mredis.list_lrange('logo_generation_queue', 0, 2)

        if not logo_requests:
            print("[Logo异步任务] 队列为空，无需处理")
            return

        print(f"[Logo异步任务] 获取到 {len(logo_requests)} 条Logo生成请求")

        for request_data in logo_requests:
            try:
                # 解析请求数据
                request_info = json.loads(request_data)
                user_id = request_info.get('user_id')
                gender = request_info.get('gender')
                fitness_level = request_info.get('fitness_level')

                print(f"[Logo异步任务] 处理用户ID: {user_id}, 性别: {gender}, 健身水平: {fitness_level}")

                # 存储处理状态到Redis
                progress_data = {
                    'status': 'processing',
                    'message': '开始生成Logo...',
                    'progress': 10,
                    'user_id': user_id,
                    'timestamp': time.time()
                }
                mredis.set_str(f"logo_progress_{user_id}", json.dumps(progress_data))

                # 调用Logo生成Agent
                result = logo_agent.generate_logo(gender, fitness_level)

                # 更新进度状态
                progress_data = {
                    'status': 'generating',
                    'message': 'Logo生成中...',
                    'progress': 50,
                    'user_id': user_id,
                    'timestamp': time.time()
                }
                mredis.set_str(f"logo_progress_{user_id}", json.dumps(progress_data))

                if result['success']:
                    # 提取图片URL
                    image_url = None
                    # 从返回结果的不同可能字段中提取图片URL
                    if result.get('data', {}).get('image_url'):
                        image_url = result['data']['image_url']
                    elif result.get('image_data'):
                        image_url = result['image_data']
                    elif result.get('data', {}).get('image_data'):
                        image_url = result['data']['image_data']

                    if image_url:
                        # 更新用户记录
                        try:
                            user = UserProfile.objects.get(id=user_id)
                            user.logo_url = image_url
                            user.save()
                            print(f"[Logo异步任务] 用户 {user_id} 的Logo已保存: {image_url}")

                            # 存储成功结果到Redis
                            result_data = {
                                'success': True,
                                'image_url': image_url,
                                'user_id': user_id,
                                'message': 'Logo生成成功！',
                                'timestamp': time.time()
                            }
                            mredis.set_str(f"logo_result_{user_id}", json.dumps(result_data))

                            # 设置结果过期时间（24小时）
                            mredis.expire(f"logo_result_{user_id}", 86400)

                        except UserProfile.DoesNotExist:
                            print(f"[Logo异步任务] 用户 {user_id} 不存在")
                            error_result = {
                                'success': False,
                                'message': '用户不存在',
                                'user_id': user_id,
                                'timestamp': time.time()
                            }
                            mredis.set_str(f"logo_result_{user_id}", json.dumps(error_result))
                            mredis.expire(f"logo_result_{user_id}", 3600)  # 1小时过期
                    else:
                        print(f"[Logo异步任务] 用户 {user_id} Logo生成成功但未获取到图片URL")
                        error_result = {
                            'success': False,
                            'message': 'Logo生成成功但未获取到图片URL',
                            'user_id': user_id,
                            'timestamp': time.time()
                        }
                        mredis.set_str(f"logo_result_{user_id}", json.dumps(error_result))
                        mredis.expire(f"logo_result_{user_id}", 3600)
                else:
                    print(f"[Logo异步任务] 用户 {user_id} Logo生成失败: {result.get('message', '未知错误')}")
                    error_result = {
                        'success': False,
                        'message': result.get('message', 'Logo生成失败'),
                        'user_id': user_id,
                        'timestamp': time.time()
                    }
                    mredis.set_str(f"logo_result_{user_id}", json.dumps(error_result))
                    mredis.expire(f"logo_result_{user_id}", 3600)

                # 从队列中删除已处理的请求
                mredis.list_del('logo_generation_queue', request_data)
                print(f"[Logo异步任务] 已从队列中删除用户 {user_id} 的请求")

            except json.JSONDecodeError as e:
                print(f"[Logo异步任务] JSON解析错误: {e}")
                # 删除无效的请求数据
                mredis.list_del('logo_generation_queue', request_data)
            except Exception as e:
                print(f"[Logo异步任务] 处理单个请求时发生错误: {e}")
                # 删除出错的请求数据
                mredis.list_del('logo_generation_queue', request_data)

                # 存储错误结果
                if 'user_id' in locals():
                    error_result = {
                        'success': False,
                        'message': f'处理请求时发生错误: {str(e)}',
                        'user_id': user_id,
                        'timestamp': time.time()
                    }
                    mredis.set_str(f"logo_result_{user_id}", json.dumps(error_result))
                    mredis.expire(f"logo_result_{user_id}", 3600)

        print("[Logo异步任务] 本轮Logo生成任务处理完成")

    except Exception as e:
        print(f"[Logo异步任务] 发生异常: {e}")
        import traceback
        print(f"[Logo异步任务] 异常堆栈: {traceback.format_exc()}")

